<template>
  <div>
    <van-form @submit="onSubmit">
      <van-nav-bar
        class="my-nav-bar"
        title="登录"
        left-text="返回"
        left-arrow
        @click-left="$router.go(-1)"
      />
      <van-field
        v-model="tel"
        type="tel"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对'
          }
        ]"
      />
      <van-field
        v-model="code"
        type="digit"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        required
        :rules="[
          { required: true, message: '验证码没有写哦!' },
          { pattern: /^\d{6}$/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="登录中..."
          loading-type="spinner"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 先导入登录接口
import { getLogin } from './user.js'
// 登录页面导入 存token函数的接口
import {saveToken} from '@/utils/token.js'
export default {
  name: 'login',
  data () {
    return {
      tel: '',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    onSubmit (values) {
      console.log('submit', values)
      this.isLoading = true
      setTimeout(() => {
        getLogin(values)
          .then(res => {
            console.log(res)
            // 引入 Toast 组件后，会自动在 Vue 的 prototype 上挂载 $toast 方法，便于在组件内调用。
            this.$toast.success({
              message: '登录成功',
              icon: 'passed'
            })
            // 登录成功后保存 token  并跳转页面
            saveToken(res.data.data)
            this.$router.push({ path: '/home' })
          })
          .catch(err => {
            this.$toast.fail({
              message: '手机号或验证码错误',
              icon: 'close'
            })
          })
          .then(() => {
            this.isLoading = false
          })
      }, 500)
    }
  }
}
</script>

<style lang="less">
.my-nav-bar {
  &.van-nav-bar {
    background-color: #3196fa;
  }
  .van-nav-bar__title {
    color: #fff;
  }
  .van-nav-bar__left {
    .van-icon-arrow-left,
    .van-nav-bar__text {
      color: #fff;
    }
  }
}
</style>
